package com.fla.aiba.api;

import com.fla.aiba.entity.user.User;
import com.fla.aiba.repository.LiveRepository;
import com.fla.aiba.repository.UserRepository;
import com.fla.aiba.service.UserService;
import com.fla.aiba.util.ComputeUtils;
import com.fla.aiba.dto.UserDto;
import com.jiai.core.tools.RestResultGenerator;
import com.jiai.exception.ServiceException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * Created by qudingyi on 2017/4/14.
 */
@RequestMapping("/api/v1/user")
@RestController
public class UserAPIController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private LiveRepository liveRepository;
    @Autowired
    private UserService userService;

    @RequestMapping(value="/live/checkLiveUser",method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public Object checkLiveUser(@RequestBody User user)throws  ServiceException{
        UserDto view=userService.getLiveUserInfo(user.getId());
        if(view!=null){
            return  RestResultGenerator.genSuccessResult(view);
        }else{
            if(!StringUtils.isEmpty(user.getBirthday())){
                SimpleDateFormat format=new SimpleDateFormat("yyy/MM/dd");
                try {
                    user.setAge(ComputeUtils.getAges(format.parse(user.getBirthday())));
                } catch (ParseException e) {

                }
            }
            user=userRepository.save(user);
            return  RestResultGenerator.genSuccessResult(userService.getLiveUserInfo(user.getId()));

        }
    }





    @RequestMapping(value ="/loadMemberView/{sex}")
    public Object loadMemberView(@PathVariable("sex") int sex)throws ServiceException{
        return RestResultGenerator.genSuccessResult(userService.loadMemberView(sex));
    }
}
